<template>
	<view>
		<view v-if="cart.length !== 0">
			<!-- 1.地址框 -->
			<hjx-address :address="address"></hjx-address>
			<!-- 2.购物车标题 -->
			<view class="cart-title">
				<text class="iconfont icon-gouwuche">购物车</text>
			</view>
			<!-- 3.购物车列表 -->
			<view>
				<hjx-goods v-for="(item,index) in cart" :key="index" :goods='item' :showCheck="true" :showNum="true"
					:allowLongTap="true" @changeNum='changeNum' @changeChecked='changeChecked'></hjx-goods>
			</view>
			<!-- 结算框 -->
			<hjx-switch :buttonText="'结算'" :showAllCheck='true' :cartData='cart' @changAllCheck="changAllCheck">
			</hjx-switch>
		</view>

		<view class="empty-cart" v-else>
			<!-- <image src="../../static/cart_empty.png" mode="" class="empty-img"></image> -->
			<text class="tip-text">购物车什么也没有空空如也</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				cart: [],
				address: {},
			}
		},
		// 不能使用onLoad,否则从商品详情页加入购物车 再点击'购物车'后,购物车没有及时更新数据
		onShow() {
			// 从缓存获取购物车数据
			this.cart = uni.getStorageSync('cart') || [];
			// 从缓存获取地址数据
			this.address = uni.getStorageSync('address') || {};
		},
		methods: {
			// 全选
			changAllCheck(e) {
				this.cart.forEach(v => v.checked = e);
				// 更改缓存中的购物车
				uni.setStorageSync('cart', this.cart);
			},
			// 修改购物车相应产品的选中状态
			changeChecked(e) {
				let index = this.cart.findIndex(v => v.goods_id == e.goods_id);
				this.cart[index].checked = e.checked;
				// 更改缓存中的购物车
				uni.setStorageSync('cart', this.cart);
			},
			// 修改购物车相应产品的数量
			changeNum(e) {
				let index = this.cart.findIndex(v => v.goods_id == e.goods_id);
				if (e.cartNum == 0) {
					this.cart.splice(index, 1);
				} else {
					this.cart[index].cartNum = e.cartNum;
				}
				// console.log(this.cart);
				// 更改缓存中的购物车
				uni.setStorageSync('cart', this.cart);
			}
		}
	}
</script>

<style>
	/* 购物车标题样式 */
	.cart-title {
		height: 40px;
		display: flex;
		align-items: center;
		padding-left: 5px;
		border-bottom: 1px solid #efefef;
	}

	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 150px;
	}

	.empty-img {
		width: 90px;
		height: 90px;
	}

	.tip-text {
		font-size: 12px;
		color: gray;
		margin-top: 15px;
	}
</style>
